import {
  VuexModule,
  Module,
  Action,
  Mutation,
  getModule
} from "vuex-module-decorators";
import { UserManagementService } from "@/openApi/user-management.v1";
import store from "@/store";
import { LoginRes, LoginTodo, UserAuthInfo } from "@/models/user";
import { MenuData } from "@/models/menu";
import { menusToRoutes_c } from "@/utils/menuToRoute";
import { addApiPortMicAppRoutes } from "@/router/micApp/main";
import {
  getLoginAuthLocalStore,
  setLoginAuthLocalStore
} from "@/utils/storage";
import { addHomeEntryRoutes, homeType } from "@/router/entry";

export interface UserState {
  loginInfo: UserAuthInfo | null;
}

@Module({ dynamic: true, store, name: "user" })
class User extends VuexModule implements UserState {
  loginInfo: UserAuthInfo | null = getLoginAuthLocalStore();

  @Mutation
  private SET_LOGININFO(data: UserAuthInfo) {
    if (data) this.loginInfo = data;
  }

  @Action
  public async Login(params: LoginTodo) {
    // 登录
    if (!this.loginInfo) {
      //判断是否登录过
      const res = await UserManagementService.userLogin({
        requestBody: params
      });
      // console.log("登录数据", res, this);
      const { optResult, msg, residualTimes, ...userAuthData } = res;
      this.SET_LOGININFO(userAuthData);
      setLoginAuthLocalStore(userAuthData); //保存登录鉴权信息进localStore
      this.AddAllRoutes();
      return userAuthData;
    } else {
      this.AddAllRoutes();
      return this.loginInfo;
    }
  }

  @Action
  public AddApiPortRoutes(val?: MenuData[]) {
    // 添加api网关路由
    let data = this.loginInfo?.roleFrontAuthInfo.menus;
    if (val) data = val;
    
    if (data) {
      const childRoutes = menusToRoutes_c(
        data,
        ["micApp", "apiPort"],
        "/micApp/apiPort"
      );
      console.log("添加api网关路由",childRoutes)
      addApiPortMicAppRoutes(childRoutes);
    }
  }

  @Action
  public AddHomeEntryRoutes(type?: homeType | string) {
    // 添加homeru 入口路由
    let userType: homeType | string | null = null;
    if (type) userType = type;
    else if (this.loginInfo?.roleType) userType = this.loginInfo.roleType;
    console.log("登录用户信息",this.loginInfo)
    if (userType) addHomeEntryRoutes(userType);
    else {
      // console.log("没有登录")
      throw new Error("没有登录")
    }
  }

  @Action
  public AddAllRoutes() {
    // 添加所有路由
    this.AddHomeEntryRoutes();
    this.AddApiPortRoutes();
    // console.log("添加所有路由",router)
  }

  // @Action
  // public Login(params: loginTodo) {
  //   // 登录
  //   return new Promise((resolve, reject) => {
  //     UserManagementService.userLogin({ requestBody: params })
  //       .then(res => {
  //         console.log("登录成功",res,this)
  //         this.SET_LOGININFO(res);
  //         resolve(res);
  //       })
  //       .catch(err => {
  //         console.log("登录异常",err)
  //         reject(err);
  //       });
  //   });
  // }
}

export const UserModule = getModule(User);
